import baostock as bs
import pandas as pd
import datetime
import backtrader as bt
import easyquotation

from util.daylink import daylink


class GetBaostockDat() :


    def   getData(self,bs,stk_code,data,frequency,fromdate,todate,getNow):
        try:


            fromdate = daylink().get_day_of_day(-2000)
            todate = daylink().get_day_of_day(0)
            #lg = bs.login(user_id='anonymous', password='123456') ,tradestatus
            field='date, code, open, high, low, close'
            if frequency =='d':
                field = 'date, code, open, high, low, close,tradestatus'

            rs = bs.query_history_k_data_plus(stk_code,
                                              field,
                                              # "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
                                              start_date='%s-%s-%s' % (
                    fromdate.year, fromdate.month, fromdate.day), end_date='%s-%s-%s' % (
                    todate.year, todate.month, todate.day),
                                              frequency=frequency,
                                              adjustflag="2")
            df_init = []
            result_list = []
            while (rs.error_code == '0') & rs.next():
                # 获取一条记录，将记录合并在一起
                d = rs.get_row_data()
                #tradestatus
                if frequency == 'd' and d[6] == 0:
                    continue
                #if d[6] == 0:
                #    continue
                #print(d)
                result_list.append(d)
            if getNow == True:
                code = stk_code.split('.', 1)
                if code[1] == '002168' :
                    print("")
                #code=stk_code.replace('sh.','')
                code =code[1]
                quotation = easyquotation.use('tencent')  # 新浪 ['sina'] 腾讯 ['tencent', 'qq']
                newdata = quotation.real(code, prefix=False).get(code)  # 支持直接指定前缀，如 'sh000001'
                newLow = float(newdata.get('low'))
                newNow = float(newdata.get('now'))
                newHigh = float(newdata.get('high'))
                newOpen = float(newdata.get('open'))
                nowdate='%s-%s-%s' % (
                        datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day)
                member = [nowdate, stk_code, newOpen, newHigh, newLow, newNow,'1']
                result_list.append(member)

            df_init = pd.DataFrame(result_list, columns=rs.fields)
            df_init = df_init.astype({ 'high': 'float', 'open': 'float', 'close': 'float', 'low': 'float'})
            df_init.date = pd.to_datetime(df_init.date)
            #if stk_code == 'sh.600325':
               #print(df_init.date)
               #print(df_init.close)

            data = bt.feeds.PandasData(dataname=df_init,

                                       datetime='date',
                                       openinterest=-1,
                                       open='open',
                                       high='high',
                                       low='low',
                                       close='close',
                                       # volume='ind',
                                       # volume='volume',
                                       fromdate=fromdate,
                                       todate=todate)


            return  data

        except Exception as e:
            return  None